<?php

namespace app\user\controller\training\log;

use app\admin\service\UserService;
use app\BaseController;
use app\model\not_del\TrainingTaskUserDelLogModel;
use app\model\training\TrainingTaskModel;
use app\model\training\TrainingTaskUserModel;
use app\model\training\TrainingTaskUserResultModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 报名记录
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $where = [];
            $userWhere = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['type_id'])){
                $where[] = ['type_id','=',$param['type_id']];
            }
            if (!empty($param['status'])){
                $where[] = ['status','=',$param['status']];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $task_id = $TrainingTaskModel->where($where)->column('id');
            if (!empty($task_id)) {
                $userWhere[] = ['task_id', 'in', $task_id];
            }else{
                $userWhere[] = ['id','=',-1];
            }
            if (!empty($param['audit_status'])) {
                $userWhere[] = ['audit_status', '=', $param['audit_status']];
            }
            if (isset($param['is_finish_front']) && strlen($param['is_finish_front']) > 0) {
                $userWhere[] = ['is_finish_front', '=', $param['is_finish_front']];
            }
            if (isset($param['is_finish_after']) && strlen($param['is_finish_after']) > 0) {
                $userWhere[] = ['is_finish_after', '=', $param['is_finish_after']];
            }
            if (isset($param['is_learning']) && strlen($param['is_learning']) > 0) {
                $userWhere[] = ['is_learning', '=', $param['is_learning']];
            }
            $userWhere[] = ['uid','=',$this->userData['id']];
            $TrainingTaskUserDelLogModel = new TrainingTaskUserDelLogModel();
            $delId = $TrainingTaskUserDelLogModel->where('uid','=',$this->userData['id'])->column('task_user_id');
            $userWhere[] = ['id','not in',$delId];
            $query = $TrainingTaskUserModel->where($userWhere);
            $data = $query->with([
                'task' => function ($query) {
                    $query->with([
                        'user' => function ($query) {
                            $query->with(['roleName']);
                        },
                        'TrainingLecturer',
                        'typeName',
                        'textbook' => function ($query) {
                            $query->with(['textbookType']);
                        }
                    ]);
                }
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|number',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $TrainingTaskModel = new TrainingTaskModel();
            $TaskInfo = $TrainingTaskModel->with([
                'user',
                'TrainingLecturer',
                'typeName',
                'textbook',
                'TrainingTaskDepartment',
                'TrainingTaskRatingScaleFront' => function($query){
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function($query){
                    $query->with(['ratingScale']);
                }
            ])->find($info['task_id']);
            $TaskInfo = $TaskInfo->toArray();
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            if (!empty($TaskInfo['TrainingTaskRatingScaleFront'])){
                foreach ($TaskInfo['TrainingTaskRatingScaleFront'] as &$value){
                    $result = $TrainingTaskUserResultModel->field('id,callable_view')->where([
                        ['task_id','=',$info['task_id']],
                        ['uid','=',$this->userData['id']],
                        ['type','=',1],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->find();
                    if ($result){
                        $value['result_id'] = $result['id'];
                        $value['callable_view'] = $result['callable_view'];
                    }else{
                        $value['result_id'] = 0;
                        $value['callable_view'] = 0;
                    }
                }
            }
            if (!empty($TaskInfo['TrainingTaskRatingScaleAfter'])){
                foreach ($TaskInfo['TrainingTaskRatingScaleAfter'] as &$value){
                    $result = $TrainingTaskUserResultModel->field('id,callable_view')->where([
                        ['task_id','=',$info['task_id']],
                        ['uid','=',$this->userData['id']],
                        ['type','=',2],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->find();
                    if ($result){
                        $value['result_id'] = $result['id'];
                        $value['callable_view'] = $result['callable_view'];
                    }else{
                        $value['result_id'] = 0;
                        $value['callable_view'] = 0;
                    }
                }
            }
            if (!empty($TaskInfo['TrainingTaskDepartment'])){
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($TaskInfo['TrainingTaskDepartment'] as &$department){
                    $department['name'] = $allDepartment[$department['department_id']]['all_name']??'--';
                }
            }
            return success([
                'info' => $info,
                'TaskInfo' => $TaskInfo
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 更新内容
     * @return bool|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|number',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['learning'])){
                $param['is_learning'] = 1;
            }
            $info->save($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 请假
     * @return bool|string
     */
    public function askForLeave(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'leave_reason|请假原因' => 'require'
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['leave_status'] == 1) throw new \Exception('请假正在审核中！');
            if ($info['leave_status'] == 2) throw new \Exception('不可重复请假！');
            $info->save([
                'leave_status' => 1,
                'leave_reason' => $param['leave_reason']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


}